﻿using AutomaticScrewLocking.domain.modbus.comm.model.entity;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading;

namespace AutomaticScrewLocking.types
{
    public class GlobalParam
    {
        private static GlobalParam instance;
        public CommParam param = new CommParam();

        public static GlobalParam getInstance()
        {
            // cas机制实现的线程安全的单例模式
            if (instance == null)
            {
                GlobalParam temp = new GlobalParam();

                Interlocked.CompareExchange(ref instance, temp, null);
            }

            return instance;

            // 线程不安全的单例模式
            /*if (instance == null)
            {
                instance = new GlobalParam();
            }
            return instance;*/
        }

        /// <summary>
        /// 加载参数
        /// </summary>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool loadParam(out string errorMsg)
        {
            bool result = false;
            errorMsg = string.Empty;
            try
            {
                string fileName = "setting.dat";

                string str = File.ReadAllText(fileName);
                param = JsonConvert.DeserializeObject<CommParam>(str);
                result = true;
            }
            catch(Exception ex)
            {
                errorMsg = ex.Message + ex.StackTrace;
            }

            return result;
        }

        /// <summary>
        /// 保存参数
        /// </summary>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool saveParam(out string errorMsg)
        {
            bool result = false;
            errorMsg = string.Empty;
            try
            {
                string fileName = "setting.dat";
                string str = JsonConvert.SerializeObject(param);
                File.WriteAllText(fileName, str);
                result = true;
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message + ex.StackTrace;
            }

            return result;
        }
    }
}
